    $(document).ready(function(){
        $('#tabs').tabs();
        $.ajaxSetup({
            cache: false,
            type: 'POST',
            dataType: 'json',
            error: function () {
                alert('Um erro de comunicação com o servidor ocorreu!');
                $('#ajax-ldr').fadeOut('fast');
            }
        });            
        $('.curtir').click(function(){
            var e = this;
            $.ajax({
                url: '/chamadas/curtir',
                processData: false,
                data: 'id=' + $(e).attr('chamada'),
                beforeSend: function() {
                    var pos = $(e).position();
                    var width = $(e).width();
                    $("#ajax-ldr").css({
                        "left": (pos.left + width + 20) + "px",
                        "top": pos.top + "px"
                    });
                    $("#ajax-ldr").show();
                },
                success: function(msg) {
                    //$(e).removeClass('curtir_nao').addClass('curtir_sim');
                    if ($(e).attr('class') == 'curtir curtir_nao') {
                        $(e).removeClass('curtir_nao').addClass('curtir_sim');
                    }
                    else {
                        $(e).removeClass('curtir_sim').addClass('curtir_nao');
                    }
                    $('#ajax-ldr').fadeOut('fast');
                }
            });
        });
        $('textarea.tinymce').tinymce({
            // Location of TinyMCE script
            script_url : '/js/tiny_mce/tiny_mce.js',

            // General options
            theme : "advanced",
//            plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",
            plugins: "autoresize,style",
            width: "80%",            

            // Theme options
            theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull",
            //theme_advanced_buttons2 : 'styleselect,formatselect,fontselect,fontsizeselect,|,forecolor,backcolor',
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "bottom",
            theme_advanced_resizing : true,

            // Example content CSS (should be your site CSS)
            content_css : "/js/tinymce/themes/advanced/skins/default/content.css",            
        });
    
//    document.getElementById('problema'+'_ifr').style.width='50%';
//    document.getElementById('problema'+'_tbl').style.width='50%';
    
    $('#ac_cliente').focus();
    
    $('#submit').button().click(function(){
        $('form').submit();
    });
    $("#data_prev").datepicker({
        monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
        dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
        dateFormat: 'dd/mm/yy'
    });



    $('#ac_cliente').autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "/colaborador/index",
                type: "POST",
                datatype: "json",
                data: {
                    q: request.term,
                    codfun :5
                },
                success: function(data) {
                    response($.map(data.colaboradores, function(item) {
                        return {
                            label: item.nome,
                            value: item.codusu
                        }
                    }))
                }
            })
        },
        minLength: 3,
        delay: 400,
        focus: function(event,ui){
            $('#ac_cliente').val(ui.item.label);
            return false;
        },
        open: function(event,ui) {
            $('#idcliente').val('');
        },
        select: function(event,ui){
            $('#idcliente').val(ui.item.value);
            $('#ac_cliente').val(ui.item.label);
            if ($('#idcliente').val()!==''){
                $.ajax({
                    url: "/contato/index",
                    processData: false,
                    data: 'cliente_id='+$('#idcliente').val(),
                    beforeSend: function (){
                        var pos = $('#ac_cliente').position();
                        var width = $('#ac_cliente').width();
                        $("#ajax-ldr").css( {
                            "left": (pos.left+width+5) + "px",
                            "top":pos.top + "px"
                        } ).fadeIn('fast');

                    },
                    success: function(msg){
                        $('#idcontato option').remove();
                        $('#idcontato').append("<option value=''>Selecione o Contato...</option>")
                        for (i = 0; i < msg.length; i++) {
                            $('#idcontato').append("<option value='"+msg[i].idcontato+"'>"+msg[i].dsnome+"</option>")
                        }
                        $('#ajax-ldr').fadeOut('fast');
                    }
                });
                $.ajax({
                    url: "/clientes/sistemas",
                    processData: false,
                    data: 'cliente_id='+$('#idcliente').val(),
                    beforeSend: function (){
                        var pos = $('#ac_cliente').position();
                        var width = $('#ac_cliente').width();
                        $("#ajax-ldr").css( {
                            "left": (pos.left+width+5) + "px",
                            "top":pos.top + "px"
                        } ).fadeIn('fast');

                    },
                    success: function(msg){
                        $('#codsis option').remove();
                        $('#codsis').append("<option value=''>Selecione o Sistema...</option>")
                        var aux = '';
                        if (msg['qtde']==1){ aux = 'selected';};
                        $.each(msg['sistemas'],function(i,n){                            
                            $('#codsis').append("<option value='"+n.codsis+"' "+aux+" >"+n.descricao+"</option>")
                        });
                        if (msg['qtde']==1){ carregamodulos();}
                        //for (i = 0; i < msg.length; i++) {
                        //    $('#codsis').append("<option value='"+msg[i].codsis+"'>"+msg[i].descricao+"</option>")
                        //}
                        $('#ajax-ldr').fadeOut('fast');
                    }
                });
            }
            return false;
        }
    });
    $('#id_depto').change(function(){
        if ($('#id_depto').val()!=''){
            $.ajax({
                url: "/funcionarios/index",
                processData: false,
                data: 'id_depto='+$('#id_depto').val(),
                beforeSend: function (){
                    var pos = $('#id_depto').position();
                    var width = $('#id_depto').width();
                    $("#ajax-ldr").css( {
                        "left": (pos.left+width+5) + "px",
                        "top":pos.top + "px"
                    } ).fadeIn('fast');

                },
                success: function(msg){
                    $('#codusures option').remove();
                    $('#codusures').append("<option value=''>Selecione o Funcionário...</option>")
                    for (i = 0; i < msg.length; i++) {
                        $('#codusures').append("<option value='"+msg[i].id+"'>"+msg[i].nome+"</option>")
                    }
                    $('#ajax-ldr').fadeOut('fast');
                }
            });
        }
    });
    function carregamodulos(){
        $.ajax({
            url: "/clientes/modulos",
            processData: false,
            data: 'sistema='+$('#codsis').val()+'&cliente='+$('#idcliente').val(),
            beforeSend: function (){
                var pos = $('#codsis').position();
                var width = $('#codsis').width();
                $("#ajax-ldr").css( {
                    "left": (pos.left+width+5) + "px",
                    "top":pos.top + "px"
                } ).fadeIn('fast');

            },
            success: function(msg){
                $('#codmod option').remove();
                $('#codmod').append("<option value=''>Selecione o Módulo</option>");
                if (msg['qtde']>0){
                    $.each(msg['contratados'],function(item, value){
                        $('#codmod').append("<option value='"+value.modulo.id+"'>"+value.modulo.descricao+"</option>")
                    });
                }
                $('#ajax-ldr').fadeOut('fast');
            }
        });
    }
    $('#codsis').change(function(){
        if ($('#codsis').val()!=''){
            carregamodulos();
        }
    });
    $('#arquivo').uploadify({
        'uploader'  : '/js/lib/uploadify/uploadify.swf',
        'script'    : '/js/lib/uploadify/uploadify.php',
        'cancelImg' : '/js/lib/uploadify/cancel.png',
        'auto'      : true,
        'folder'    : '/uploads',
        'multi'     : true,
        onComplete  : completou
    });

    // $('.arquivos').click(function(){
    //    var aux = $(this).attr('arq');
    //    window.open('/chamadas/arquivo/id/'+aux,'Anexo....');
    //    return false;
    // });
    
    function completou(e,q,file,response){
        var aux = new String;
        if ($('#files').val()==''){
            aux = escape(file.name);
        }else{
            aux = $('#files').val()+','+escape(file.name);
        }
        $('#files').val(aux);
    };
    $('#novaativ').click(function(){
        if ($('#novaatividade').is(':visible')){
            $('#novaatividade').slideUp('fast');
        }else{
            $('#novaatividade').slideDown('fast');
        }
        return false;
    });
    //-----------------------------------------------------------
    $('#ac_responsavel_atividade').autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "/funcionarios/index",
                type: "POST",
                datatype: "json",
                data: {
                    q: request.term
                },
                success: function(data) {
                    response($.map(data, function(item) {
                        return {
                            label: item.nome,
                            depto: item.id_depto,
                            value: item.id
                        }
                    }))
                }
            })
        },
        focus: function(event,ui){
            $('#ac_responsavel_atividade').val(ui.item.label);
            return false;
        },
        open: function(event,ui) {
            $('#idresponsavel').val('');
        },
        select: function(event,ui){
            $('#idresponsavel').val(ui.item.value);
            $('#id_depto_ativ').val(ui.item.depto);
            $('#ac_responsavel_atividade').val(ui.item.label);
            return false;
        },
        minLength: 3,
        delay: 300
    });
    //-----------------------------------------------------------


    $('#btngravar').button();
    $('#ac_rotina').autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "/rotinas/index",
                type: "POST",
                datatype: "json",
                data: {
                    q: request.term
                },
                success: function(data) {
                    response($.map(data, function(item) {
                        return {
                            label: item.nome,
                            value: item.id_rotina
                        }
                    }))
                }
            })
        },
        focus: function(event,ui){
            $('#ac_rotina').val(ui.item.label);
            return false;
        },
        open: function(event,ui) {
            $('#id_rotina').val('');
        },
        select: function(event,ui){
            $('#id_rotina').val(ui.item.value);
            $('#ac_rotina').val(ui.item.label);
            return false;
        },
        minLength: 3,
        delay: 300
    });

    $('#id_depto_ativ').change(function(){
        $('#ac_responsavel_atividade').val('');
    });
    $('#btngravar').click(function(){
        $.ajax({
            url: "/chamadas/novaatividade",
            processData: false,
            data: 'climov='+$('#id').val()+'&codusures='+$('#idresponsavel').val()+'&id_depto='+$('#id_depto_ativ').val()+
            '&id_rotina='+$('#id_rotina').val()+'&obs='+$('#ac_obs').val()+'&clientele='+$('#clientele').attr('checked')+
            '&fechar='+$('#baixar').attr('checked'),
            beforeSend: function (){
                //alert($('#id').val());
                var pos = $('#btngravar').position();
                var width = $('#btngravar').width();
                $("#ajax-ldr").css( {
                    "left": (pos.left+width+32) + "px",
                    "top":pos.top+12 + "px"
                } ).fadeIn('fast');

            },
            success: function(msg){
                $('#accordion').
                append($('<h3>').append($('<a>').text('Atualizada neste atendimento por você!'))).
                append($('<div>').
                    append($('<p>').text($('#ac_obs').val()))).
                accordion('destroy').accordion();
                $('#idresponsavel').val('');
                $('#id_depto').val('');
                $('#id_rotina').val('');
                $('#ac_obs').val('');
                $('#horas').val();
                $('#minutos').val('');
                $('#ac_responsavel_atividade').val('');
                $('#ac_rotina').val('');
                $('#novaatividade').slideUp('fast');
                $('#ajax-ldr').fadeOut('fast');
            }
        });
    });
})